<template>
  <div>
    <el-row type="flex" justify="space-between">
      <el-col :span="6">
        <el-button type="primary" plain size="small" @click="showAddSource('add')">新增内容源</el-button>
      </el-col>
      <el-col :span="18">
        <el-form :inline="true" type="flex" justify="space-between">

          <!-- 搜索条件 -->
          <el-form-item label="一级分类">
            <el-select v-model="searchLv1" @change="getcategoryLv2( lv2 = searchLv1)" clearable placeholder="一级分类">
              <el-option v-for="item in categoryLv1" :key="item.id" :value="item.code" :label="item.name">
                {{ item.name }}
              </el-option>
            </el-select>
          </el-form-item>

          <el-form-item label="二级分类">
            <el-select v-model="searchLv2" clearable multiple placeholder="请先选择一级分类">
              <el-option v-for="item in categoryLv2" :key="item.id" :value="item.code" :label="item.name">
                {{ item.name }}
              </el-option>
            </el-select>
          </el-form-item>

          <el-form-item label="爬取状态">
            <el-select v-model="crawling" clearable placeholder="爬取状态">
              <el-option :key="true" :value="true" :label="'爬取中'">爬取中</el-option>
              <el-option :key="false" :value="false" :label="'未爬取'">未爬取</el-option>
            </el-select>
          </el-form-item>

          <el-form-item>
            <el-input placeholder="搜索标签" v-model="tags"></el-input>
          </el-form-item>

          <el-form-item>
            <el-input placeholder="名称搜索" v-model="name"></el-input>
          </el-form-item>
          <el-form-item>
            <el-button type="primary" icon="el-icon-search" @click="getlists">搜索
            </el-button>
          </el-form-item>
        </el-form>
      </el-col>
    </el-row>

    <!-- list -->
    <template>
      <div class="content-wrapper" v-for="(item, index) in content" :key="index">
        <div style="display: flex;">
          <img :src=" $defaults.baseURL +'/icon?icon=' + item.icon" alt=""
            style="width:80px;height:80px;margin-right:10%;">
          <div style="width:80%;">
            <div class="flex">
              <h1>{{ item.platform_name }}</h1>
              <div style="display: flex;" v-if="item.crawl">
                <span class="crawling"></span>
                <span> 正在爬取中</span>
              </div>

              <div style="display: flex;" v-else>
                <span class="crawling" style="background-color:red;"></span>
                <span> 未爬取</span>
              </div>
            </div>
            <div>
              <span style="margin-right:50px;">一级分类 : <span
                  style="margin-left:10px;">{{ item.platform_category_lv1 }}</span></span>
              <span>二级分类 : <span style="margin-left:10px;">{{ item.categoryLv2Names }}</span></span>
            </div>
            <div class="flex">
              <div>
                <el-tag style="margin:20px 10px 0 0;" type="success" v-for="(option, index) in item.platform_tagArr"
                  :key="index"> {{ option }} </el-tag>
              </div>

              <!-- 编辑展开 -->
              <div style="margin-top:10px;">
                <el-button size="mini" @click="showAddSource('edit',item.id,index)">编辑</el-button>
                <el-button size="mini" @click="seeMoreData(index)">展开</el-button>
              </div>

            </div>
          </div>
        </div>
        <div v-if="seeMore[index]" style="margin-top:20px;" class="flex">
          <div>
            <p>累计爬取数据：{{ item.historyCount }}</p>
            <p>近7天日均更新：{{ item.historyCount7DayAvg }}</p>
          </div>
          <line-chart :chart-data=" item.historyCount7Day " style="height: 300px;width:60%;" />
        </div>
      </div>

      <div class="block">
        <el-pagination class="pageNation" @size-change="handleSizeChange" @current-change="handleCurrentChange"
          :current-page="currentPage" :page-sizes="[10, 15, 30, 50]" :page-size="pageSize"
          layout="total, sizes, prev, pager, next, jumper" :total="total">
        </el-pagination>
      </div>
    </template>

    <!-- 编辑？新增内容源 -->
    <el-dialog title="新增内容源" :visible.sync="addSourceVisible" width="80%">
      <el-form label-width="120px">
        <el-form-item label="内容源名称">
          <el-input v-model="addSourcelist.name" placeholder="中文，用户可见" auto-complete="off">
          </el-input>
        </el-form-item>
        <el-form-item label="内容源URL">
          <el-input v-model="addSourcelist.url" placeholder="中文，用户可见" auto-complete="off">
          </el-input>
        </el-form-item>

        <el-form-item label="标签">
          <el-tag :key="tag" v-for="tag in addSourcelist.tags" closable :disable-transitions="false"
            @close="handleClose(tag)">
            {{tag}}
          </el-tag>
          <el-input class="input-new-tag" v-if="inputVisible" v-model="inputValue" ref="saveTagInput" size="small"
            @keyup.enter.native="handleInputConfirm" @blur="handleInputConfirm">
          </el-input>
          <el-button v-else class="button-new-tag" size="small" @click="showInput">+ New Tag</el-button>
          <p style="color:red;font-size:8px;">(中文、用户可见，最多5个，逗号隔开)</p>
        </el-form-item>

        <el-form-item label="一级分类">
          <el-select v-model="addSourcelist.categoryLv1Code"
            @change="getcategoryLv2(lv2 = addSourcelist.categoryLv1Code)" clearable placeholder="一级分类">
            <el-option v-for="item in categoryLv1" :key="item.id" :value="item.code" :label="item.name">{{ item.name }}
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="二级分类">
          <el-select v-model="addSourcelist.categoryLv2Codes" clearable multiple placeholder="请先选择一级分类">
            <el-option v-for="item in categoryLv2" :key="item.id" :value="item.code" :label="item.name">{{ item.name }}
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="上传icon">
          <el-upload class="upload-demo" :limit="1" :action="uploadUrl" :on-success="handleAvatarSuccess"
            :on-remove="handleRemove" :file-list="fileList" list-type="picture">
            <el-button size="small" type="primary">点击上传</el-button>
            <div slot="tip" class="el-upload__tip">只能上传jpg/png文件，且不超过500kb</div>
          </el-upload>
        </el-form-item>
        <el-form-item label="是否在时间轴里展示？">
          <el-select v-model="addSourcelist.homeView" clearable placeholder="是否展示文件？">
            <el-option :value="true" key="true" label="是">
            </el-option>
            <el-option :value="false" key="false" label="否">
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="备注">
          <el-input v-model="addSourcelist.remark" type="textarea"></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button type="info" @click="addSourceVisible = false">取 消</el-button>
        <el-button type="info" @click="addSource">保 存</el-button>
      </span>
    </el-dialog>

  </div>
</template>

<script>
  import lineChart from "./components/lineChart";

  export default {
    name: 'contentManagnment',
    components: {
      lineChart
    },

    data() {
      return {
        seeMore: [],
        crawling:'',

        addSourceVisible: false,
        content: [],

        inputVisible: false,
        inputValue: '',

        categoryLv1: [],
        categoryLv2: [],
        lv2: '',

        //内容源列表
        addSourcelist: {
          id: "",
          name: "",
          url: "",
          categoryLv1Code: "",
          categoryLv2Codes: [],
          tags: [],
          homeView: null,
          remark: "",
          file: null,
        },

        fileList: [],

        // 条件筛选
        searchLv1: '',
        searchLv2: [],
        tags: '',
        name: '',

        uploadUrl: '',

        //分页对象参数
        pageNo: 1,
        pageSize: 10,
        total: 1,
        currentPage: 1,
      }
    },

    mounted() {
      this.uploadUrl = `${this.$defaults.baseURL}/upload`;
      this.getcategoryLv1();
      this.getlists();
    },

    methods: {
      // 展开收起
      seeMoreData(index) {
        this.$set(this.seeMore, index, !this.seeMore[index]);
      },

      // 添加tags
      handleClose(tag) {
        this.addSourcelist.tags.splice(this.addSourcelist.tags.indexOf(tag), 1);
      },
      showInput() {
        this.inputVisible = true;
        this.$nextTick(_ => {
          this.$refs.saveTagInput.$refs.input.focus();
        });
      },
      handleInputConfirm() {
        let inputValue = this.inputValue;

        if (inputValue) {
          this.addSourcelist.tags.push(inputValue);
        }
        this.inputVisible = false;
        this.inputValue = '';
      },

      // 上传图片
      // 删除图片
      handleRemove(file, fileList) {
        this.file = '';
        // console.log(file, fileList);
      },
      // 上传成功
      handleAvatarSuccess(res, file) {
        this.file = file.response.resultParm.resource;
        this.$message.success('上传成功');
        // console.log(this.file,'45354');
      },

      // 对象改数组
      printObject(obj) {
        var actualData = [],
          dateData = [],
          avg = 0;
        Object.keys(obj).forEach(function (key) {
          dateData.push(key);
          actualData.push(obj[key]);
        });
        for (var i = 0; i < actualData.length; i++) {
          var el = actualData[i];
          avg += el * 1;
        }

        return {
          actualData: actualData,
          dateData: dateData,
          avg: Math.floor(avg / 7)
        }
      },

      // 获取内容源List
      getlists() {
        this.seeMore = [];
        var data = {
          categoryLv1: this.searchLv1,
          name: this.name,
          tags: this.tags,
          crawling: this.crawling,
          pageNo: this.pageNo,
          pageSize: this.pageSize
        }

        if (this.searchLv2.length > 0) {
          data.categoryL2 = this.searchLv2.toString();
        }

        let conf = {
          url: "/platforms",
          method: "get",
          params: data
        };
        this.$axios(conf).then(res => {
          if (res.responseCode === 200) {
            for (var i = 0; i < res.resultParm.resource.list.length; i++) {
              // tag
              var el = res.resultParm.resource.list[i].platform_tag1;
              if (el) {
                var elArr = el.split(',');
                res.resultParm.resource.list[i].platform_tagArr = elArr;
              }

              // 7天日均数据转换
              var Count7DayArr = this.printObject(res.resultParm.resource.list[i].historyCount7Day);
              res.resultParm.resource.list[i].historyCount7DayAvg = Count7DayArr.avg;
              res.resultParm.resource.list[i].historyCount7Day = {
                actualData: Count7DayArr.actualData,
                dateData: Count7DayArr.dateData
              }

              // 展开收起
              this.seeMore[i] = false;
            }

            this.content = res.resultParm.resource.list;

            this.pageSize = res.resultParm.resource.pageSize;
            var num = res.resultParm.resource.total;
            this.total = parseInt(num);
          } else {
            this.$message.error("操作失败：" + res.message);
          }
        })
      },

      handleSizeChange(val) {
        this.pageSize = val;
        this.getlists();
      },
      handleCurrentChange(val) {
        this.pageNo = val;
        this.getlists();
      },

      //获取一级内容源分类
      getcategoryLv1() {
        let conf = {
          url: "/platformcategoryLv1",
          method: "get",
        };
        this.$axios(conf).then(res => {
          if (res.responseCode === 200) {
            this.categoryLv1 = res.resultParm.resource;
          } else {
            this.$message.error("操作失败：" + res.message);
          }
        })
      },

      //获取二级内容源分类
      getcategoryLv2() {
        this.searchLv2 = [];

        if (this.lv2) {
          let conf = {
            url: "/platformcategoryLv2",
            method: "get",
            params: {
              pcode: this.lv2
            }
          };
          this.$axios(conf).then(res => {
            if (res.responseCode === 200) {
              this.categoryLv2 = res.resultParm.resource;
            } else {
              this.$message.error("操作失败：" + res.message);
            }
          })
        } else {
          this.categoryLv2 = [];
        }
      },

      // 打开 编辑？新增？
      showAddSource(key, id, index) {
        this.addSourceVisible = true;

        if (key === 'edit') {
          this.addSourcelist.id = id;
          this.addSourcelist.name = this.content[index].platform_name;
          this.addSourcelist.url = this.content[index].url;
          this.addSourcelist.categoryLv1Code = this.content[index].platform_category_lv1_code;

          if (this.content[index].platform_category_lv1_code) {
            this.lv2 = this.content[index].platform_category_lv1_code;
            this.getcategoryLv2();
          }

          if (this.content[index].platform_category_lv2) {
            var elArr = this.content[index].platform_category_lv2.split(',');
            this.addSourcelist.categoryLv2Codes = elArr;
          }

          if (this.content[index].platform_tagArr) {
            this.addSourcelist.tags = this.content[index].platform_tagArr;
          }

          this.addSourcelist.homeView = this.content[index].homeView;
          this.addSourcelist.remark = this.content[index].remark;
          this.file = this.content[index].icon;
        } else if (key === 'add') {

          // 重置
          this.addSourcelist.id = null;
          this.addSourcelist.name = null;
          this.addSourcelist.url = null;
          this.addSourcelist.categoryLv1Code = null;
          this.addSourcelist.categoryLv2Codes = [];

          this.addSourcelist.tags = [];
          this.addSourcelist.homeView = '';
          this.addSourcelist.remark = '';
          this.file = null;
        }
      },

      // 数组转字符转
      str(arr) {
        var str = '';
        for (var i = 0; i < arr.length; i++) {
          var el = arr[i];
          if (i < arr.length - 1) {
            str += (el + ',')
          } else {
            str += el
          }
        }
        return str
      },

      // 确认添加？ 编辑？ 内容源
      addSource() {
        this.addSourceVisible = true;

        var tagStr = this.str(this.addSourcelist.tags);

        var data = {
          id: this.addSourcelist.id,
          name: this.addSourcelist.name,
          url: this.addSourcelist.url,
          categoryLv1Code: this.addSourcelist.categoryLv1Code,
          tags: tagStr,
          homeView: this.addSourcelist.homeView,
          remark: this.addSourcelist.remark,
          icon: this.file
        }

        if (this.addSourcelist.categoryLv2Codes.length > 0) {
          data.categoryLv2Codes = this.addSourcelist.categoryLv2Codes.toString();
        }

        let conf = {
          url: "/platform",
          method: "post",
          data: data
        };
        this.$axios(conf).then(res => {
          if (res.responseCode === 200) {
            this.$message.success('操作成功');
            this.addSourceVisible = false;

            // 置空
            this.searchLv1 = null;
            this.searchLv2 = [];
            this.tags = null;
            this.name = null;

            this.getlists();
          } else {
            this.$message.error("操作失败：" + res.message);
          }
        })
      }
    }
  }

</script>

<style>
  .content-wrapper {
    margin: 20px 0 0 10%;
    width: 60%;
    box-shadow: 1px 1px 5px rgba(35, 34, 38, 0.15);
    padding: 20px;
    font-size: 12px;
    position: relative;
  }

  .flex {
    display: flex;
    justify-content: space-between;
    align-items: center;
  }

  .type {
    font-size: 20px;
  }

  .crawling {
    display: inline-block;
    width: 16px;
    height: 16px;
    background-color: rgba(82, 196, 26, 1);
    border-radius: 50%;
  }

  .margin {
    margin-bottom: 10px;
  }

  .left {
    display: block;
    margin-right: 10px;
  }

  .block {
    margin: 50px 0 0 30%;
  }

  .el-tag+.el-tag {
    margin-left: 10px;
  }

  .button-new-tag {
    margin-left: 10px;
    height: 32px;
    line-height: 30px;
    padding-top: 0;
    padding-bottom: 0;
  }

  .input-new-tag {
    width: 90px;
    margin-left: 10px;
    vertical-align: bottom;
  }

</style>
